<template>
  <div class="sql-generator-container">
    <h2 class="title">SQL生成工具</h2>

    <div class="input-section">
      <el-input
          v-model="baseSQLName"
          placeholder="请输入数据库名称"
          clearable
          class="database-input"
      />
      <el-button
          type="primary"
          @click="handleSubmit"
          class="generate-btn"
          :loading="isLoading"
      >
        生成SQL
      </el-button>
    </div>

    <div class="result-section" v-if="generatedSql">
      <h3>生成结果：</h3>
      <el-card>
        <pre class="sql-code">{{ generatedSql }}</pre>
        <el-button
            type="success"
            icon="Copy"
            @click="copyToClipboard"
            class="copy-btn"
        >
          复制SQL
        </el-button>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue"
import { ElMessage, ElMessageBox } from "element-plus";
import {BaseResponse, useTableSqlService} from "@/api/Table/TableSqlApi.js"
const { generateSql } = useTableSqlService()
import {sqlStore} from '@/store/sql/sql.js'

// 所属数据库名字
const baseSQLName = ref<string>("")
// 生成的SQL结果
const generatedSql = ref<string>("")
// 加载状态
const isLoading = ref<boolean>(false)

const handleSubmit = async () => {
  // 输入验证
  if (!baseSQLName.value.trim()) {
    ElMessage.warning("请输入数据库名称")
    return
  }

  try {
    isLoading.value = true
    // 发起生成sql的请求
    const response = await generateSql({
      databaseName: baseSQLName.value,
    })as BaseResponse<string>
    if (response && response.data?.data) {
      generatedSql.value = response.data?.data
      ElMessage.success("SQL生成成功")
      sqlStore.setSql1(response.data.data)
    } else {
      ElMessage.warning("未生成有效的SQL")
    }
  } catch (error) {
    console.error("生成SQL失败", error)
    ElMessage.error("生成SQL失败，请稍后重试")
  } finally {
    isLoading.value = false
  }
}

// 复制到剪贴板
const copyToClipboard = () => {
  if (!generatedSql.value) return

  navigator.clipboard.writeText(generatedSql.value)
      .then(() => {
        ElMessage.success("已复制到剪贴板")
      })
      .catch(() => {
        ElMessage.error("复制失败，请手动复制")
      })
}
</script>

<style scoped>
.sql-generator-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.input-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.database-input {
  flex: 1;
}

.result-section {
  margin-top: 20px;
}

.sql-code {
  white-space: pre-wrap;
  word-wrap: break-word;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-family: monospace;
  overflow-x: auto;
  max-height: 400px;
}

.copy-btn {
  margin-top: 10px;
  float: right;
}
</style>